package light.head.controller.sys;

import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import light.head.config.ConfigParm;
import light.head.constant.Msg;
import light.head.constant.Parm;
import light.head.constant.Sys;
import light.head.constant.Url;
import light.head.dao.sys.OrganDAO;
import light.head.dao.sys.OrganDetailsDAO;
import light.head.dao.sys.UserInfoDAO;
import light.head.enm.RESULT;
import light.head.framework.base.SupporterController;
import light.head.framework.entity.PageBean;
import light.head.framework.utils.PinYinUtils;
import light.head.model.Organ;
import light.head.model.OrganDetails;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;


@Controller
@RequestMapping(Url.C_ORGAN)
public class OrganController extends SupporterController {
	
	private OrganDAO organDAO;
	private UserInfoDAO userDAO;
	private OrganDetailsDAO odsDAO;

	@RequestMapping(Url.INIT)
	public ModelAndView init(HttpServletRequest request, HttpServletResponse response) throws Exception {
		return new ModelAndView(Url.ORGAN_INIT);
	}

	@RequestMapping(Url.QUERY)
	public ModelAndView query(HttpServletRequest request, HttpServletResponse response) throws Exception {
		PageBean pb = createPageBean(request);
		Map<String, String> map = createQueryMapByParmName(request, Parm.NAME, Parm.OTC, Parm.DELETED,Parm.IS_USING);
		
		if (organDAO.findByMap(map, pb) == RESULT.SUCCESS)
			request.setAttribute(Parm.PAGE_BEAN, pb);
		
		return new ModelAndView(Url.ORGAN_LIST);
	}

	@RequestMapping(Url.EDIT)
	public ModelAndView edit(Integer code, Integer pc, HttpServletRequest request, HttpServletResponse response) throws Exception {
		
		if (null != code) {
			Organ cbi = organDAO.getOrgan(code);
			if (null != cbi) {
				OrganDetails ods = odsDAO.getByOc(cbi.getCode());
				cbi.setDetails(ods);
			}
			OrganDetails od = odsDAO.getByOc(code);
			Organ organ = organDAO.get(code);
			//企业地图
			if(od != null){
				StringBuffer str = new StringBuffer("[");
				str.append("{\"info\":");
				str.append("[");
				str.append("\"<a href='" + ConfigParm.getContextPath() + "organindex.html?code="+ organ.getCode() + "'>" + organ.getName() + "</a>\",");
				str.append("\"电话:" + ((null == od.getPhone()) ? "暂无" : od.getPhone()) + "地址:" + ((null == od.getAddress()) ? "暂无" : od.getAddress()) + "\"");
				str.append("],");
				str.append("\"lng\":\"" + ((null == od.getLongitude()) ? "non" : od.getLongitude()) + "\",");
				str.append("\"lat\":\"" + ((null == od.getLatitude()) ? "non" : od.getLatitude()) + "\"},");
				str.deleteCharAt(str.length() - 1).append("]");
				request.setAttribute(Parm.ORGANDETAIL, str.toString());
				if(od.getLongitude() != null && od.getLatitude() != null){
					request.setAttribute(Parm.LONGITUDE, od.getLongitude());
					request.setAttribute(Parm.LATITUDE, od.getLatitude());
				}
			}
			request.setAttribute(Parm.ORGAN, cbi);
		} else if (null != pc) {
			Organ parent = organDAO.getOrgan(pc);
			if (null != parent) {
				Organ o = new Organ();
				o.setPc(parent.getCode());
				o.setPn(parent.getName());
				o.setOtc(parent.getOtc());
				o.setOtn(parent.getOtn());
				request.setAttribute(Parm.ORGAN, o);
			}
		}

		String userList = userDAO.userList(cu_organCode(request));
		request.setAttribute(Parm.USER_LIST, userList);
		return new ModelAndView(Url.ORGAN_EDIT);
	}

	@RequestMapping(Url.AID_EDIT)
	public ModelAndView aidEdit(Integer code, Integer pc, HttpServletRequest request, HttpServletResponse response) throws Exception {
		if (null != code) {
			Organ cbi = organDAO.getOrgan(code);
			if (null != cbi) {
				OrganDetails ods = odsDAO.getByOc(cbi.getCode());
				cbi.setDetails(ods);
			}
			request.setAttribute(Parm.ORGAN, cbi);
		} else if (null != pc) {
			Organ parent = organDAO.getOrgan(pc);
			if (null != parent) {
				Organ o = new Organ();
				o.setPc(parent.getCode());
				o.setPn(parent.getName());
				o.setOtc(parent.getOtc());
				o.setOtn(parent.getOtn());
				request.setAttribute(Parm.ORGAN, o);
			}
		}

		String userList = userDAO.userList(cu_organCode(request));
		request.setAttribute(Parm.USER_LIST, userList);
		return new ModelAndView(Url.ORGAN_AID_EDIT);
	}
	
	@RequestMapping(Url.SAVE)
	public void save(Organ cbi, HttpServletRequest request, HttpServletResponse response) throws Exception {
		RESULT result = RESULT.ERROR;
		if (cbi.getPc() == null)
			cbi.setPc(Sys.ZERO);
		
		if (isNotNull(cbi.getName())) {
			String pingyin = PinYinUtils.cn2py(cbi.getName());
			cbi.setPinyin((pingyin.length() > 49) ? pingyin.substring(0, 49) : pingyin);
			cbi.setPy(PinYinUtils.cn2first(cbi.getName()));
		}
		
		if (cbi.getCode() != null) {
			result = organDAO.update(cbi);
			// 修改详情
			if (RESULT.SUCCESS == result) {
				result = odsDAO.update(cbi.getDetails());
				// 没有就添加详情
				if (RESULT.NOT_FIND == result || RESULT.PARAMETER_ERROR == result) {
					cbi.getDetails().setOc(cbi.getCode());
					result = odsDAO.add(cbi.getDetails());
				}
			}
			
		} else {
			cbi.setCu(cu_code(request));
			cbi.setCt(new Date());
			cbi.setDeleted(false);
			result = organDAO.add(cbi);
			
			// 添加详情
			if (RESULT.SUCCESS == result) {
				cbi.getDetails().setOc(cbi.getCode());
				result = odsDAO.add(cbi.getDetails());
			}
		}
		
		if (RESULT.SUCCESS == result) {
			organDAO.loadAll();
			print(response, Msg.SUCCESS);
		} else
			print(response, Msg.ERROR);
	}
	
	@RequestMapping(Url.SHIELD)
	public void shield(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String code = request.getParameter(Parm.CODE);
		if (!isNotNull(code)) {
			print(response, Msg.PARAMETER_ERROR);
			return;
		}
		Organ cbi = organDAO.get(Integer.parseInt(code));
		if (null == cbi) {
			print(response, Msg.NOT_FIND);
			return;
		}

		cbi.setDeleted(true);
		if (organDAO.update(cbi) == RESULT.SUCCESS) {
			organDAO.loadAll();
			print(response, Msg.SUCCESS);
		} else
			print(response, Msg.ERROR);
	}
	
	@RequestMapping(Url.UN_SHIELD)
	public void unshield(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String code = request.getParameter(Parm.CODE);
		if (!isNotNull(code)) {
			print(response, Msg.PARAMETER_ERROR);
			return;
		}
		Organ cbi = organDAO.get(Integer.parseInt(code));
		if (null == cbi) {
			print(response, Msg.NOT_FIND);
			return;
		}
		
		cbi.setDeleted(false);
		if (organDAO.update(cbi) == RESULT.SUCCESS) {
			organDAO.loadAll();
			print(response, Msg.SUCCESS);
		} else
			print(response, Msg.ERROR);
	}
	
	@RequestMapping(Url.TREE)
	public ModelAndView tree(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String code = request.getParameter(Parm.CODE);
		if (isNotNull(code)) {
			Organ o = organDAO.getOrgan(Integer.parseInt(code));
			if (null != o) {
				StringBuffer tree = new StringBuffer();
				tree.append("p.add('" + o.getCode() + "','-1','" + o.getName() + "');");
				aidTree(tree, o.getSonList());
				request.setAttribute(Parm.TREE, tree);
				request.setAttribute(Parm.ORGAN, o);
			}
		}
		return new ModelAndView(Url.ORGAN_TREE);
	}
	private void aidTree(StringBuffer tree, List<Organ> list) {
		if (null == tree || null == list || list.size() == 0)
			return;
		for (Organ o : list) {
			tree.append("p.add('" + o.getCode() + "','" + o.getPc() + "','" + o.getName() + "');");
			aidTree(tree, o.getSonList());
		}
	}	

	/** 下面几个方法是辅助其他模块查询用户时使用 */
	@RequestMapping(Url.AID_INIT)
	public ModelAndView aidQueryInit(HttpServletRequest request, HttpServletResponse response) throws Exception {
		request.setAttribute(Parm.ID, request.getParameter(Parm.ID));
		request.setAttribute(Parm.NAME, request.getParameter(Parm.NAME));
		String code = request.getParameter(Parm.CODE);

		List<Organ> list = organDAO.getAll();
//		Integer root = organDAO.getRoot(Integer.parseInt(code)).getCode();
		
		
		if (list != null) {
			StringBuffer tree = new StringBuffer();
			for (Organ o : list) {
				if (null != o && o.getPc() == 0) {
					tree.append("p.add('" + o.getCode() + "','-1','" + o.getName() + "');");
					aidTree(tree, o.getSonList());
					request.setAttribute(Parm.TREE, tree);
					request.setAttribute(Parm.ORGAN, o);
				}
			}
		}

		request.setAttribute(Parm.CODE, code);
		return new ModelAndView(Url.ORGAN_AID_INIT);
	}

	@RequestMapping(value = Url.EDIT_SELF)
	public ModelAndView editSelf(HttpServletRequest request, HttpServletResponse response) throws Exception {
		Integer cu_organCode = cu_organCode(request);
		if (null == cu_organCode) {
			request.setAttribute(Parm.INFO, Msg.NO_LOGIN);
			return new ModelAndView(Url.BS_LOGIN);
		}
		Organ organ = organDAO.get(cu_organCode);
		request.setAttribute(Parm.ORGAN, organ);
		return new ModelAndView(Url.ORGAN_EDIT_SELF);
	}
	@RequestMapping(value = Url.SAVE_SELF)
	public ModelAndView saveSelf(Organ organ, HttpServletRequest request, HttpServletResponse response) throws Exception {
		Integer cu_organCode = cu_organCode(request);
		
		if (null == cu_organCode) {
			request.setAttribute(Parm.INFO, Msg.NO_LOGIN);
			return new ModelAndView(Url.BS_LOGIN);
		}
		
		organ.setCode(cu_organCode);
		if (organDAO.update(organ) == RESULT.SUCCESS) 
			print(response, Msg.SUCCESS);
		else 
			print(response, Msg.ERROR);
		
		return null;
	}
	
	
	
	@Autowired
	public void setOrganDAO(OrganDAO organDAO) {
		this.organDAO = organDAO;
	}
	@Autowired
	public void setUserDAO(UserInfoDAO userDAO) {
		this.userDAO = userDAO;
	}

	@Autowired
	public void setOdsDAO(OrganDetailsDAO odsDAO) {
		this.odsDAO = odsDAO;
	}
	
	
}
